package logrus.beanmock.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import logrus.beanmock.ScenarioController;

public class ScenarioFilter implements Filter {

    private final ScenarioController mockScenarioController;

    private final ScenarioExtractor scenarioExtractor;

    public ScenarioFilter(ScenarioController mockScenarioController) {
        this(mockScenarioController, new RequestParamScenarioExtractor());
    }

    public ScenarioFilter(final ScenarioController mockScenarioController,
            final ScenarioExtractor scenarioExtractor) {
        this.mockScenarioController = mockScenarioController;
        this.scenarioExtractor = scenarioExtractor;
    }

    public void destroy() {
        //
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String[] scenarios = scenarioExtractor.getScenarios(request);
        mockScenarioController.begin(scenarios);
        try {
            chain.doFilter(request, response);
        } finally {
            mockScenarioController.end();
        }
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        //
    }

}
